const { verify } = require('jsonwebtoken');
const db = require('../config/database');
const { Logger } = require('../utils/logger');

// JWT验证中间件
const authenticateToken = async (req, res, next) => {
  const startTime = Date.now();
  try {
    // 从Authorization header获取token
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
    
    if (!token) {
      return res.status(403).json({
        code: 403,
        message: '登录过期，请重新登录'
      });
    }

    // 验证token
    const decoded = verify(token, process.env.JWT_SECRET || 'your-secret-key');
    
    // 从数据库获取用户信息 - 使用更健壮的错误处理
    let rows;
    let retryCount = 0;
    const maxRetries = 2;
    
    while (retryCount <= maxRetries) {
      try {
        [rows] = await db.execute(
          'SELECT id, nickname, phone, role, status FROM user WHERE id = ?',
          [decoded.id]
        );
        break; // 查询成功，跳出循环
      } catch (dbError) {
        retryCount++;
        
        // 如果是连接错误并且还可以重试
        if ((dbError.code === 'ECONNRESET' || dbError.code === 'PROTOCOL_CONNECTION_LOST') && retryCount <= maxRetries) {
          // 等待一小段时间后重试，避免立即重试
          await new Promise(resolve => setTimeout(resolve, 100));
          continue;
        }        
        // 如果是连接错误，返回友好的错误信息
        if (dbError.code === 'ECONNRESET' || dbError.code === 'PROTOCOL_CONNECTION_LOST') {
          return res.status(500).json({
            code: 500,
            message: '数据库连接异常，请稍后再试'
          });
        }
        
        throw dbError; // 重新抛出其他类型的错误
      }
    }
    
    if (rows.length === 0) {
      return res.status(401).json({
        code: 401,
        message: '用户不存在'
      });
    }
    
    const user = rows[0];
    
    // 检查用户状态
    if (user.status === 0) {
      return res.status(401).json({
        code: 401,
        message: '账户已被禁用'
      });
    }
    
    // 将用户信息添加到请求对象
    req.user = user;
    next();
    
  } catch (error) {
    console.error('JWT验证失败:', error);    
    if (error.name === 'JsonWebTokenError') {
      return res.status(403).json({
        code: 403,
        message: '登录过期，请重新登录'
      });
    }
    
    if (error.name === 'TokenExpiredError') {
      return res.status(403).json({
        code: 403,
        message: '登录过期，请重新登录'
      });
    }
    
    // 数据库连接错误的特殊处理
    if (error.code === 'ECONNRESET' || error.code === 'PROTOCOL_CONNECTION_LOST') {
      return res.status(500).json({
        code: 500,
        message: '数据库连接异常，请稍后再试'
      });
    }
    
    return res.status(500).json({
      code: 500,
      message: process.env.NODE_ENV === 'development' ? error.message : '服务器内部错误'
    });
  }
};

// 可选的JWT验证中间件（不强制要求token）
const optionalAuth = async (req, res, next) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];

    if (!token) {
      req.user = null;
      return next();
    }

    const decoded = verify(token, process.env.JWT_SECRET || 'your-secret-key');
    
    const [rows] = await db.execute(
      'SELECT id, nickname, phone, role, status FROM user WHERE id = ?',
      [decoded.id]
    );
    
    if (rows.length > 0 && rows[0].status !== 0) {
      req.user = rows[0];
    } else {
      req.user = null;
    }
    
    next();
    
  } catch (error) {
    // 可选验证失败时不返回错误，只是设置user为null
    req.user = null;
    next();
  }
};

module.exports = {
  authenticateToken,
  optionalAuth
};